#include "device.h"

#include "peripheral.h"

static void rtc_alarm_handler(const struct tm *_tm)
{
  printf("alarm: %s\n", asctime(_tm));
  Device_IRQHandler(vRTC_0, _tm, sizeof(struct tm));
}
/**
 * @brief  读取RTC
 * @note
 * @param  dev：虚拟设备
 * @param  data：数据存放的位置
 * @param  len：数据长度
 * @param  param：此处没用到,传0即可
 * @return 成功/失败
 */
static int32_t RTC_Read(VirtualHardware_enum_t dev, void *data, uint32_t len, uint32_t param)
{
  struct tm dateTime = {0};

  if (dev == vRTC_0)
  {

    rtc_time_get(&dateTime);

    ((uint8_t *)data)[0] = (uint8_t)dateTime.tm_year - 100;
    ((uint8_t *)data)[1] = (uint8_t)dateTime.tm_mon + 1;
    ((uint8_t *)data)[2] = (uint8_t)dateTime.tm_mday;
    ((uint8_t *)data)[3] = (uint8_t)dateTime.tm_hour;
    ((uint8_t *)data)[4] = (uint8_t)dateTime.tm_min;
    ((uint8_t *)data)[5] = (uint8_t)dateTime.tm_sec;

    // printf("rtc: %d.%d.%d %d:%d:%d\r\n", dateTime.tm_year - 100, dateTime.tm_mon + 1, dateTime.tm_mday, dateTime.tm_hour, dateTime.tm_min, dateTime.tm_sec);

    return 0;
  }
  return -1;
}

/**
 * @brief  写入RTC
 * @note  写入的日期数据必须合法
 * @param  dev：虚拟设备
 * @param  data：写入数据
 * @param  len：数据长度
 * @param  param：此处没用到,传0即可
 * @return 成功/失败
 */
static int32_t RTC_Write(VirtualHardware_enum_t dev, void *data, uint32_t len, uint32_t param)
{
  uint32_t date, month, year, sec, min, hour;
  struct tm tm = {0};

  year = (uint32_t)((uint8_t *)data)[0];
  month = (uint32_t)((uint8_t *)data)[1];
  date = (uint32_t)((uint8_t *)data)[2];
  hour = (uint32_t)((uint8_t *)data)[3];
  min = (uint32_t)((uint8_t *)data)[4];
  sec = (uint32_t)((uint8_t *)data)[5];

  // printf("set rtc time: 20%02d.%02d.%02d %02d:%02d:%02d\r\n", year, month, date, hour, min, sec);

  tm.tm_year = year + 2000 - 1900;
  tm.tm_mon = month - 1;
  tm.tm_mday = date;
  tm.tm_hour = hour;
  tm.tm_min = min;
  tm.tm_sec = sec;
  if (dev == vRTC_0 && param == 1)
  {
    printf("set rtc alarm time: 20%02d.%02d.%02d %02d:%02d:%02d\r\n", year, month, date, hour, min, sec);
    rtc_alarm_set(&tm, rtc_alarm_handler);
    return 0;
  }

  if (dev == vRTC_0)
  {
    printf("set rtc time: 20%02d.%02d.%02d %02d:%02d:%02d\r\n", year, month, date, hour, min, sec);
    rtc_time_set(&tm, NULL);
    //Device_IRQHandler(vRTC_0, &tm, sizeof(struct tm));
    return 0;
  }

  return -1;
}

/**
 * @brief RTC初始化
 *
 * @note
 */
static void RTC_Init(void)
{
  struct tm tm = {0};
  /* 1、初始化硬件 */
  rtc_init();

  tm.tm_year = 2023 - 1900;
  tm.tm_mon = 1 - 1;
  tm.tm_mday = 1;
  tm.tm_hour = 8;
  tm.tm_min = 8;
  tm.tm_sec = 0;

  // Set time
  rtc_time_set(&tm, NULL);
  // Run
  rtc_start();

  /* 2、将底层设备具体操作接口，挂到设备控制块里面 */
  Device_stu_t *dcb = Device_GetDeviceCtrlBlock(vRTC);
  dcb->write = RTC_Write;
  dcb->read = RTC_Read;
  printf("rtc init\r\n");
}
INIT_DEVICE_EXPORT(RTC_Init);
